package com.kingdee.openimport.patch_service.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * redis哨兵配置 采用redisTemplate
 * Created by Niki on 2018/4/23 11:23
 */
//@Configuration
public class RedisSentinelConfig {

    @Value("${spring.redis.sentinel.master}")
    private String masterName;
    @Value("${spring.redis.sentinel.nodes}")
    private String nodes;
    @Bean
    @ConfigurationProperties(prefix = "spring.reids.jedis.pool")
    public JedisPoolConfig getPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        return poolConfig;
    }

    @Bean
    public RedisSentinelConfiguration getSentinelConfiguration() {
        Set<String> sentinelHostAndPorts = null ;
        RedisSentinelConfiguration configuration = new RedisSentinelConfiguration(masterName, getSentinelHostAndPorts(nodes));
        RedisPassword redisPassword = RedisPassword.of("xtkingdee".toCharArray());
        configuration.setPassword(redisPassword);
        return configuration;
    }

    private Set<String> getSentinelHostAndPorts(String nodes) {
        Set<String> sentinels = new HashSet<>();
        if (nodes != null) {
            String[] sentinelArr = nodes.split(",");
            if (sentinelArr != null) {
                for (String sen : sentinelArr) {
                    if (sen != null) {
                        sentinels.add(sen);
                    }
                }
            }
        }
        return sentinels;
    }

    @Bean
    public JedisConnectionFactory getConnectionFactory() {
        RedisSentinelConfiguration sentinelConfig = getSentinelConfiguration();
        JedisPoolConfig poolConfig = getPoolConfig();
        JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfig, poolConfig);
        return factory;
    }

    /**
     * 注意redisTemplate中序列化的设置
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate();
        JedisConnectionFactory connectionFactory = getConnectionFactory();
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}
